package com.huawei.hwclouds.lubanops.demo.common.client.impl;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

class ApacheHttpClientHelp {
    private ApacheHttpClientHelp() {
    }

    static HttpClientConnectionManager getConnectionManager(SSLContext sslContext) {
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry
            = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
            PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
        return new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    }

    static HttpClient getHttpclient(HttpClientConnectionManager connectionManager, int idleTimeInSeconds) {
        return HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .evictIdleConnections(idleTimeInSeconds, TimeUnit.SECONDS) //如果连接10秒之内没有使用，那么就断开连接。主要应用在中间网络被桥段
            .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy())
            .setRetryHandler(new DefaultHttpRequestRetryHandler())
            .build();
    }
}
